package com.flyoil.petromp.ui.fragment.fragment_home;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cnpc.fyutils.Constants;
import com.cnpc.fyutils.SystemBarUtils;
import com.cnpc.fyutils.SystemUtils;
import com.cnpc.fyutils.ToastUtils;
import com.cnpc.fyviewlibrary.view.GridScrollview;
import com.cnpc.pullrefresh.ItemDecoration.HomeDeviderDecoration;
import com.cnpc.pullrefresh.ItemDecoration.MyDeviderDecoration;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.adapter.adapter_home.ItemHomeMenuAdapter;
import com.flyoil.petromp.adapter.adapter_matter.ItemMatterAdapter;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.base.BaseFragment;
import com.flyoil.petromp.base.BaseRecyAdapter;
import com.flyoil.petromp.entity.entity_home.BannerListEntity;
import com.flyoil.petromp.entity.entity_home.HomeMatterListEntity;
import com.flyoil.petromp.entity.entity_home.HomeMenuEntity;
import com.flyoil.petromp.entity.entity_matter.MatterEntity;
import com.flyoil.petromp.entity.entity_notice.NoticeEntity;
import com.flyoil.petromp.ui.activity.activity_course.CourseListActivity;
import com.flyoil.petromp.ui.activity.activity_matter.MatterListActivity;
import com.flyoil.petromp.ui.activity.activity_matter.OrderMessageActivity;
import com.flyoil.petromp.ui.activity.activity_me.MyMessageActivity;
import com.flyoil.petromp.ui.activity.activity_notice.NoticeListActivity;
import com.flyoil.petromp.ui.activity.activity_repertory.RepertoryListListActivity;
import com.flyoil.petromp.utils.Dialog.Dialog_util;
import com.flyoil.petromp.utils.MoccaPreferences;
import com.flyoil.petromp.utils.OrderUtl.OrderListUtil;
import com.flyoil.petromp.view.LooperTextView;
import com.flyoil.petromp.view.RollViewPagerFitXY;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by songzhiiyn on 2017/9/27.
 * 首页
 */

public class HomeFragment extends BaseFragment {
    private ItemMatterAdapter adapter;
    private RollViewPagerFitXY mRollViewPager;//自定义viewpager
    private View include_banner;//banner的布局
    private LinearLayout mViewPagerContainer;//存放viewpager的组件
    private LinearLayout mPointsContainer;//圆点部分
    private ArrayList<View> mDotLists;//圆点控件
    private LooperTextView looperTextView;//公告轮播功能
    private GridScrollview grid;
    private ItemHomeMenuAdapter homeMenuAdapter;
    private ImageView img_message;//我的消息
    private double banner_hight_ratio = 2.3;//banner高和宽的比例
    private View view_statusbar;
    private LinearLayout line_data_hint;
    private TextView tv_hint;
    private HomeDeviderDecoration homeDeviderDecoration;


    @Override
    protected int getContentViewResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {
        super.initViews();
        recyclerView = $(R.id.listrecy_home_fragment);
        view_statusbar = $(R.id.view_statusbar);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        homeDeviderDecoration = new HomeDeviderDecoration(mContext, R.color.main_line_color, 1);
        homeDeviderDecoration.setStartCount(2);
        recyclerView.addItemDecoration(homeDeviderDecoration);
        adapter = new ItemMatterAdapter(mContext);
        recyclerView.setAdapter(adapter);
        httpModel = new HttpModel();
        initTopView();
        initDefaultViews();

    }


    /**
     * 初始化状态栏
     */
    private void initDefaultViews() {
        //设置状态栏高度
        if (view_statusbar != null) {
            LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    SystemBarUtils.getStatusBarHeight(mContext)
            );
            view_statusbar.setBackgroundResource(R.color.activity_backgroud_lucency);
            view_statusbar.setLayoutParams(ll);
        }
        view_statusbar.setVisibility(View.VISIBLE);
        if (recyclerView != null) {
            recyclerView.settPullViewHeight(SystemBarUtils.getStatusBarHeight(mContext));//主界面因为没有填充状态栏，所以多添加一个距离
        }
    }

    @Override
    protected void initdatas() {
        super.initdatas();
        getHomeMatterList();
        getBannerData();
        getNoticeList();
        initHomeMenuData();
    }

    @Override
    protected void onRefreshData() {
        super.onRefreshData();
        initdatas();
    }

    @Override
    public void onResume() {
        if (isFirstLoadck == false)
            onRefreshData();
        super.onResume();
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        adapter.setOnItemClickListener(onItemClickListener);
        setOnRefreshListener(false);
    }

    /**
     * 列表的点击事件
     */
    private BaseRecyAdapter.OnItemClickListener onItemClickListener = new BaseRecyAdapter.OnItemClickListener() {
        @Override
        public void Onclick(int position, Object data) {
            //判断用户是否设置了签名，如果尚未签名让用户去设置签名
            if (MoccaPreferences.signature_seted.get() == false) {
                Dialog_util.showSetSigantureDialog(mContext);
                return;
            }
            Intent intent = new Intent(getActivity(), OrderMessageActivity.class);
            MatterEntity entity = (MatterEntity) data;
            intent.putExtra("order_type", entity.getBillType());
            intent.putExtra("id", entity.getId());
            startActivity(intent);
        }
    };

    private void initTopView() {
        View recyleHeader = LayoutInflater.from(mContext).inflate(R.layout.item_home_top_view_layout, null);
        include_banner = recyleHeader.findViewById(R.id.include_banner);
        mViewPagerContainer = include_banner.findViewById(R.id.banner_viewpager);
        mPointsContainer = include_banner.findViewById(R.id.ll_points);
        img_message = recyleHeader.findViewById(R.id.img_item_home_top_view_message);
        looperTextView = recyleHeader.findViewById(R.id.looper_item_home_view);
        looperTextView.setOnClickListener(onClickListener);
        grid = recyleHeader.findViewById(R.id.grid_item_home_top_view);
        line_data_hint = recyleHeader.findViewById(R.id.line_loading_data_hint);
        tv_hint = recyleHeader.findViewById(R.id.tv_hint_data_message);
        line_network = recyleHeader.findViewById(R.id.line_network_hint_layout);
        line_network.setVisibility(View.GONE);
        homeMenuAdapter = new ItemHomeMenuAdapter(mContext);
        grid.setAdapter(homeMenuAdapter);
        grid.setOnItemClickListener(onMenuItemClickListener);
        img_message.setOnClickListener(onClickListener);
        recyclerView.addHeaderView(recyleHeader);
    }


    /**
     * 功能按钮列表的item点击事件
     */
    private AdapterView.OnItemClickListener onMenuItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //判断用户是否设置了签名，如果尚未签名让用户去设置签名
            if (MoccaPreferences.signature_seted.get() == false) {
                Dialog_util.showSetSigantureDialog(mContext);
                return;
            }
            HomeMenuEntity entity = (HomeMenuEntity) homeMenuAdapter.getItem(i);
            int action = Integer.valueOf(entity.getAction());
            Intent intent = new Intent();
            switch (action) {
                case 1://待办事项
                    intent.setClass(mContext, MatterListActivity.class);
                    intent.putExtra("matter_type", 1);
                    break;
                case 2://已办事项
                    intent.setClass(mContext, MatterListActivity.class);
                    intent.putExtra("matter_type", 2);
                    break;
                case 3://流程列表
                    intent.setClass(mContext, CourseListActivity.class);
                    break;
                case 4://供应商列表
                    intent.setClass(mContext, RepertoryListListActivity.class);
                    break;
            }
            startActivity(intent);

        }
    };
    /**
     * 控件的点击事件
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //判断用户是否设置了签名，如果尚未签名让用户去设置签名
            if (MoccaPreferences.signature_seted.get() == false) {
                Dialog_util.showSetSigantureDialog(mContext);
                return;
            }
            switch (view.getId()) {
                case R.id.looper_item_home_view:
                    startActivity(new Intent(mContext, NoticeListActivity.class));
                    break;
                case R.id.img_item_home_top_view_message:
                    startActivity(new Intent(mContext, MyMessageActivity.class));
                    break;
            }
        }
    };

    /**
     * 初始化轮播图
     */
    private void initRollViewData(List<String> images) {
        if (Constants.sScreenHeight == 0 || Constants.sScreenWidth == 0) {
            SystemUtils.getScreen(mContext);//获取屏幕的高度和宽度
        }
        mViewPagerContainer.setLayoutParams(new RelativeLayout.LayoutParams(Constants.sScreenWidth,
                (int) (Constants.sScreenWidth / banner_hight_ratio)));
        include_banner.setLayoutParams(new LinearLayout.LayoutParams(Constants.sScreenWidth,
                (int) (Constants.sScreenWidth / banner_hight_ratio)));
        // TODO: 2017/2/7
        if (images != null) {
            prepareViewPage(mContext, images);
        }

    }


    /**
     * 获取进度追踪的列表
     */
    private void getHomeMatterList() {
        httpModel.getHomeMatterList(new HashMap<String, Object>(), new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                HomeMatterListEntity entity = null;
                if (model instanceof HomeMatterListEntity) {
                    entity = (HomeMatterListEntity) model;
                }
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData() != null) {
                    onRefreshDataSucceed();
                    if (entity.getData().size() > 0) {
                        homeDeviderDecoration.setStartCount(0);
                        line_data_hint.setVisibility(View.GONE);
                        recyclerView.setBackgroundColor(getResources().getColor(R.color.activity_backgroud));
                        List<MatterEntity> matterEntities = new ArrayList<>();
                        for (int i = 0; i < entity.getData().size(); i++) {
                            HomeMatterListEntity.DataBean dataBean = entity.getData().get(i);
                            MatterEntity matterEntity = new MatterEntity();
                            matterEntity.setId(dataBean.getBillId());
                            matterEntity.setBillType(dataBean.getBillTypeLabel());
                            matterEntity.setBillCreateTime(dataBean.getCreatedTimeLabel());
                            matterEntity.setSn(dataBean.getSn());
                            matterEntity.setFlowName(dataBean.getTitle());
                            matterEntities.add(matterEntity);
                        }
                        adapter.setDataList(matterEntities);
                        recyclerView.notifyDataSetChanged();
                    } else {
                        homeDeviderDecoration.setStartCount(2);
                        line_data_hint.setVisibility(View.VISIBLE);
                        recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
                        tv_hint.setText("暂无进度");
                    }
                } else {
                    homeDeviderDecoration.setStartCount(2);
                    line_data_hint.setVisibility(View.VISIBLE);
                    recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
                    tv_hint.setText("暂无进度");
                }
            }

            @Override
            public void onFailure(String msg) {
                onRefreshDataError();
                homeDeviderDecoration.setStartCount(2);
                line_data_hint.setVisibility(View.VISIBLE);
                recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
                tv_hint.setText("数据加载失败");
            }
        });
    }


    /**
     * 获取首页banner图列表
     */
    private void getBannerData() {
        httpModel.getBannerList(null, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                BannerListEntity entity = null;
                if (model instanceof BannerListEntity) {
                    entity = (BannerListEntity) model;
                }
                List<String> imgs = new ArrayList<>();
                imgs.clear();
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData() != null) {
                    for (int i = 0; i < entity.getData().size(); i++) {
                        imgs.add(entity.getData().get(i).getUrl());
                    }
                } else {
                    imgs.add("null");
                    imgs.add("null");
                    imgs.add("null");
                }
                initRollViewData(imgs);
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    /**
     * 初始化首页轮播公告的部分
     */
    private void getNoticeList() {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", 1);
        map.put("pageSize", 3);
        httpModel.getNoticeList(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                NoticeEntity entity = null;
                if (model instanceof NoticeEntity) {
                    entity = (NoticeEntity) model;
                } else {
                    ToastUtils.show_toast(model.getMessage());
                }
                if (entity != null && entity.getData() != null && entity.getData().getList() != null && model.getCode() == ConstantNetworkCode.SuccedCode) {
                    if (entity.getData().getList().size() > 0) {
                        List<String> data_notice = new ArrayList<>();
                        for (int i = 0; i < entity.getData().getList().size(); i++) {
                            data_notice.add(entity.getData().getList().get(i).getTitle());
                        }
                        looperTextView.setTipList(data_notice);
                    } else {
                        List<String> data_notice = new ArrayList<>();

                        looperTextView.setTipList(data_notice);
                    }
                } else {
                    List<String> data_notice = new ArrayList<>();
                    data_notice.add("暂无公告");
                    looperTextView.setTipList(data_notice);
                }

            }

            @Override
            public void onFailure(String msg) {
                List<String> data_notice = new ArrayList<>();
                data_notice.add("暂无公告");
                looperTextView.setTipList(data_notice);
            }
        });
    }

    /**
     * 初始化首页按钮列表
     */
    private void initHomeMenuData() {
        List<HomeMenuEntity> menuEntities = new ArrayList<>();
        menuEntities.add(new HomeMenuEntity("待办事项", R.mipmap.daibanshixiang, "1"));
        menuEntities.add(new HomeMenuEntity("已办事项", R.mipmap.yibanshixiang, "2"));
        menuEntities.add(new HomeMenuEntity("流程列表", R.mipmap.liuchengliebiao, "3"));
        menuEntities.add(new HomeMenuEntity("入库信息", R.mipmap.rukuxinxi, "4"));
        homeMenuAdapter.setdate(menuEntities);
    }

    /**
     * 将数据赋值到轮播图上，将加载的图片显示出来
     *
     * @param mContext
     * @param list
     */
    private void prepareViewPage(final Context mContext, final List<String> list) {
        List<String> imageUrlList = new ArrayList<String>();
        if (list == null || list.size() < 1) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            imageUrlList.add(list.get(i));
        }
        if (imageUrlList.size() <= 1) {
            mPointsContainer.setVisibility(View.GONE);
        } else {
            mPointsContainer.setVisibility(View.VISIBLE);
        }
        initDots(list.size());
        mRollViewPager = new RollViewPagerFitXY(getActivity().getApplication(), mContext, mDotLists, R.mipmap.main_banner_bg_pic_white,
                R.mipmap.main_banner_bg_pic_active, null);
        mRollViewPager.setLayoutParams(new LinearLayout.LayoutParams(Constants.sScreenWidth,
                (int) (Constants.sScreenWidth / banner_hight_ratio)));
        mRollViewPager.setImageUrl(imageUrlList);
        mRollViewPager.startRoll();
        mViewPagerContainer.removeAllViews();
        mViewPagerContainer.addView(mRollViewPager);
    }


    /**
     * 初始化圆点
     *
     * @param size
     */
    private void initDots(int size) {
        mDotLists = new ArrayList<View>();
        mPointsContainer.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    SystemUtils.dip2px(8, mContext), SystemUtils.dip2px(8, mContext)
            );
            layoutParams.setMargins(10, 0, 10, 10);
            ImageView m = new ImageView(mContext);
            if (i == 0) {
                m.setBackgroundResource(R.mipmap.main_banner_bg_pic_active);
            } else {
                m.setBackgroundResource(R.mipmap.main_banner_bg_pic_white);
            }
            m.setLayoutParams(layoutParams);
            mDotLists.add(m);
            mPointsContainer.addView(m);
        }

    }
}
